<template>
  <DialogCom v-model="dialogComVisible" :title="index == 1 ? '添加菜单' :  '编辑菜单'"
             width="30%" submit-text="确定" @clear-form="clearForm(formRef)" @submit-form="submitForm(formRef)">
    <div class="dialogCom_wrapper">
      <el-form :model="form.data" ref="formRef" :rules="rules as FormRules" label-width="130px">
        <el-form-item label="上级菜单：">
          <el-tree-select
              v-model="form.data.parentId"
              :data="menusTree.data"
              check-strictly
              clearable
              :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="菜单类型：" prop="menuType">
          <el-radio-group v-model="form.data.menuType" size="default">
            <el-radio-button v-for="item in menuTypeList.data" :key="item.value" :label="item.value">{{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单图标：" prop="icon" v-if="form.data.menuType !== 3">
          <IconPicker v-model="form.data.icon"/>
        </el-form-item>
        <el-form-item label="菜单名称：" prop="menuName">
          <el-input v-model="form.data.menuName" placeholder="请输入菜单名称" clearable
                    style="width: 202px !important;"/>
        </el-form-item>
        <el-form-item label="排序：" prop="menuSort">
          <el-input-number
              v-model="form.data.menuSort"
              :min="0"
              controls-position="right"
              style="width: 202px !important;"
          />
        </el-form-item>
        <el-form-item label="路由地址：" prop="path" v-if="form.data.menuType !== 3">
          <template #label>
            <div class="tooltip-wrapper">
              <el-tooltip
                  content="访问的路由地址，如：`/system/user/index`，如外网地址需内链访问则`http(s)://localhost:8080/system/user/index`"
                  placement="top">
                <QuestionFilled class="tooltipIcon"/>
              </el-tooltip>
              路由地址：
            </div>
          </template>
          <el-input v-model="form.data.path" placeholder="请输入路由地址" clearable
                    style="width: 202px !important;"/>
        </el-form-item>
        <el-form-item label="组件路径：" prop="component" v-if="form.data.menuType !== 1 && form.data.menuType !== 3">
          <template #label>
            <div class="tooltip-wrapper">
              <el-tooltip content="访问的组件路径，如：`/system/user/index`，默认在`views`目录下" placement="top">
                <QuestionFilled class="tooltipIcon"/>
              </el-tooltip>
              组件地址：
            </div>
          </template>
          <el-input v-model="form.data.component" placeholder="请输入组件路径" clearable
                    style="width: 202px !important;"/>
        </el-form-item>
        <el-form-item label="权限字符：" prop="permission" v-if="form.data.menuType !== 1">
          <template #label>
            <div class="tooltip-wrapper">
              <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                          placement="top">
                <QuestionFilled class="tooltipIcon"/>
              </el-tooltip>
              权限字符：
            </div>
          </template>
          <el-input v-model="form.data.permission" placeholder="请输入权限字符" clearable
                    style="width: 202px !important;"/>
        </el-form-item>
        <el-form-item label="是否缓存" prop="isKeepAlive" v-if="form.data.menuType !== 1 && form.data.menuType !== 3">
          <template #label>
            <div class="tooltip-wrapper">
              <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                <QuestionFilled class="tooltipIcon"/>
              </el-tooltip>
              是否缓存：
            </div>
          </template>
          <el-radio-group v-model="form.data.isKeepAlive">
            <el-radio :label="1">缓存</el-radio>
            <el-radio :label="0">不缓存</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示状态" prop="menuVisible" v-if="form.data.menuType !== 3">
          <template #label>
            <div class="tooltip-wrapper">
              <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                <QuestionFilled class="tooltipIcon"/>
              </el-tooltip>
              显示状态：
            </div>
          </template>
          <el-radio-group v-model="form.data.menuVisible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
  </DialogCom>
</template>

<script setup lang="ts">
import DialogCom from '@/components/Dialog/index.vue'
import {ElMessage} from "element-plus";
import type {FormInstance, FormRules} from "element-plus";
import baseRequest from "@/service/baseRequest";
import {QuestionFilled} from "@element-plus/icons-vue";
import IconPicker from '@/components/IconPicker/index.vue'

const props = withDefaults(defineProps<{ index: number | string, id?: number | string }>(), {
  index: '',
  id: '',
})
const emits = defineEmits(['refreshTheList'])
const {index, id} = toRefs(props)

const formRef = ref()
let dialogComVisible = ref<boolean>(false)
let form = reactive<Record<string, any>>({
  data: {
    parentId: '',
    menuType: 1,
    menuName: '',
    menuSort: null,
    path: '',
    icon: '',
    component: '',
    permission: '',
    isKeepAlive: 0,
    menuVisible: 1,
  }
})
const menusTree = reactive({
  data: []
})
const menuTypeList = reactive({
  data: [
    {name: '目录', value: 1},
    {name: '菜单', value: 2},
    {name: '按钮', value: 3},
  ]
})
const rules = reactive<FormRules>({
  menuName: [
    {required: true, message: '请输入菜单名称', trigger: 'blur'}
  ],
  menuSort: [
    {required: true, message: '请输入排序', trigger: ['blur', 'change']}
  ],
  path: [
    {required: true, message: '请输入路由地址', trigger: 'blur'}
  ],
  icon: [
    {required: true, message: '请选择菜单图标', trigger: ['blur', 'change']}
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
        if (valid) {
          const sendData = JSON.parse(JSON.stringify(form.data))
          console.log(sendData)
          if (index.value == 1) {
            const createTheContractRes = await baseRequest.post('/addMenu', sendData) as any
            if (createTheContractRes.code == 200) {
              ElMessage.success('新增菜单成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          } else {
            sendData.id = id.value
            const updateTheContractRes = await baseRequest.post('/updateMenu', sendData) as any
            if (updateTheContractRes.code == 200) {
              ElMessage.success('更新菜单成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          }
        }
      }
  )
}
const clearForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.data = {
    parentId: '',
    menuType: 1,
    menuName: '',
    menuSort: null,
    path: '',
    icon: '',
    component: '',
    permission: '',
    isKeepAlive: 0,
    menuVisible: 1,
  } as any
  formEl.resetFields()
}
const dropDownBoxQuery = async () => {
  const treeListRes = await baseRequest.get('/menuTreeList', {}) as any
  if (treeListRes.code == 200) {
    menusTree.data = treeListRes.data.list
  }
}
//回显
const backShow = async () => {
  if (index.value != 1) {
    const backShowRes = await baseRequest.get('/getMenuInfo', {id: id.value}) as any
    if (backShowRes.code == 200) {
      form.data.path = backShowRes.data.path
      form.data.icon = backShowRes.data.icon
      form.data.parentId = backShowRes.data.parentId
      form.data.menuType = backShowRes.data.menuType
      form.data.menuName = backShowRes.data.menuName
      form.data.menuSort = backShowRes.data.menuSort
      form.data.component = backShowRes.data.component
      form.data.permission = backShowRes.data.permission
      form.data.isKeepAlive = backShowRes.data.isKeepAlive
      form.data.menuVisible = backShowRes.data.menuVisible
    }
  }
}
defineExpose({dialogComVisible, backShow, dropDownBoxQuery})
</script>

<style lang="scss" scoped>
.dialogCom_wrapper {
  max-height: 550px;
  padding: 0 30px 0 30px;
  overflow: auto;
}

.detailForm_wrapper {
  width: 90%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tooltip-wrapper {
  display: flex;
  align-items: center;
}

.tooltipIcon {
  width: 15px;
  margin-right: 5px;
}
</style>
